import { BASE_API_URL } from "../config/uniConfig";
import { useUserStore } from "../stores";


interface RequestOptions {
  url: string;
  data?: any;
  method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
  type?: string;
  noAuth?: boolean; // 新增：是否需要认证（默认需要）
}

interface ApiResponse<T = any> {
  code: number;
  data: T;
  message?: string;
  [key: string]: any;
}

/**
 * 封装请求方法
 * @param datas 请求参数
 * @returns Promise 返回请求结果
 */
function request<T = any>(datas: RequestOptions): Promise<ApiResponse<T>> {
  return new Promise((resolve, reject) => {
    // 判断是否为完整URL
    const userStore = useUserStore();
    const isFullUrl =
      datas.url.startsWith("http://") || datas.url.startsWith("https://");
    const requestUrl = isFullUrl ? datas.url : BASE_API_URL + datas.url;

    uni.request({
      url: requestUrl,
      data: datas.data || {},
      method: datas.method || "GET",
      header: {
        Authorization: "Bearer " + userStore.token, // 条件添加token
        "content-type": datas.type || "application/json;charset=UTF-8",
      },
      timeout: 10000,
      success: (res: any) => {
        const response = res.data as ApiResponse<T>;
        console.log("response", response);
        // 处理错误状态码
        if (response.code !== 200) {
          handleResponseError(response.code, response.msg);
          return reject(response);
        }

        resolve(response);
      },
      fail: (err: any) => {
        uni.hideLoading();
        reject(err);
      },
    });
  });
}
/**
 * 处理API返回的错误
 */
function handleResponseError(code: number, msg?: string): void {
  //以下目前只处理了未登录/登录失效、无权限、和其他错误处理
  switch (code) {
    case 401:
      uni.showToast({
        title: "登录已过期，请重新登录",
        icon: "none",
        image: "",
        duration: 1500,
        mask: false,
      });
      userStore.logout(); // 清除token
      break;
    case 403:
      uni.showToast({
        title: msg || "无权限访问",
        icon: "none",
      });
      break;
    default:
      uni.showToast({
        title: msg || "请求失败",
        icon: "none",
      });
  }
}

export default request;
